import { message } from 'antd';
import { useRef, useState } from 'react';
import { useDrsState } from 'umi';
import { createContainer } from 'unstated-next';

import { SearchForm } from '@szzj/ds';
import { useAntdTable, useRequest } from '@szzj/hooks';

import {
  postDelAppUser,
  queryRoleList,
  queryRoleListAuthed,
  queryUserList,
  updateUserStatus,
} from '@/services/permission/user';
import useAppCode from './useAppCode';
import useDetail from './useDetail';
import useEdit from './useEdit';

export default createContainer(() => {
  const { appCode, appName, userAppCode } = useAppCode();
  const { userInfo } = useDrsState();
  const isAdmin = userInfo?.role?.roleType?.code === 'SUPER_ADMIN';
  const updateUserStatusCode = userInfo?.role?.updateUserStatus?.code;
  const roleDataType = userInfo?.currentDataRoleType?.code;
  const isAreaPermission = roleDataType === 'AREA' || roleDataType === 'AREA_NEXT';

  const editHooks = useEdit();
  const detailHooks = useDetail();
  const isFirstLoading = useRef<boolean>(true);

  // 搜索表单
  const [tableForm] = SearchForm.useForm();

  // 组织code
  const [deptCode, setDeptCode] = useState<string>();

  // 用户列表
  const tableHooks = useAntdTable(
    async ({ current, pageSize }, { deptCode: formDeptCode, ...params }) => {
      if (!roleDataType) {
        return { list: [], total: 0 };
      }
      if (!formDeptCode && isAreaPermission && isFirstLoading?.current) {
        tableForm.setFieldsValue({ deptCode: userInfo?.currentDeptCode });
      }
      const res = await queryUserList({
        current: current,
        pageSize,
        appCode,
        userAppCode,
        ...params,
        ...(isAreaPermission && isFirstLoading?.current
          ? { deptCode: !formDeptCode ? userInfo?.currentDeptCode : formDeptCode }
          : { deptCode: formDeptCode }),
      });

      isFirstLoading.current = false;
      return {
        list: res.data?.list || [],
        total: res.data?.totalItem || 0,
      };
    },
    {
      form: tableForm,
      refreshDeps: [deptCode, roleDataType],
    },
  );

  // 应用-角色 关联数据
  const roleReq = useRequest(
    async () => {
      const res = await queryRoleList({
        appCode,
        userAppCode,
      });
      if (res.success) {
        return res.data;
      }
      return [];
    },
    {
      //TODO: userInfo获取时序不稳定，应该页面渲染就能拿到
      refreshDeps: [isAdmin],
    },
  );

  // 应用-角色-受角色影响 关联数据
  const roleAuthedReq = useRequest(
    async () => {
      const res = await queryRoleListAuthed({
        appCode,
        userAppCode,
      });
      if (res.success) {
        // 非超管不可配置超管角色
        return (
          res.data
            // 仅保留启用状态角色
            .filter((item) => item.status?.code === '1')
            .filter((item) => item.roleType?.code !== 'SUPER_ADMIN' || isAdmin)
        );
      }
      return [];
    },
    {
      //TODO: userInfo获取时序不稳定，应该页面渲染就能拿到
      refreshDeps: [isAdmin],
    },
  );

  // 设置用户状态
  async function onUpdateUserStatus(id: number, userStatus: '1' | '0') {
    const res = await updateUserStatus({
      id,
      userStatus,
      userAppCode,
    });
    if (res.success) {
      message.success('操作成功！');
      tableHooks.refresh();
    }
  }

  const postDelAppUserRequest = useRequest(
    async ({ appCode, userCode }: { appCode: string; userCode: string | number }) => {
      const res = await postDelAppUser({
        appCode,
        userCode,
      });
      if (res?.success) {
        message.success('删除成功');
        tableHooks.refresh();
      }
      return res?.data;
    },
    {
      manual: true,
    },
  );

  return {
    drsAppCode: userAppCode,
    appCode,
    appName,
    tableForm,
    deptCode,
    setDeptCode,
    tableHooks,
    editHooks,
    detailHooks,
    roleDataType,
    roleReq,
    roleAuthedReq,
    onUpdateUserStatus,
    isAdmin,
    isAreaPermission,
    updateUserStatusCode,
    postDelAppUserRequest,
  };
});
